#!/usr/bin/env python
#coding=utf8

"""
@Author: hongxing.fan
@Date: 2015-08-06 星期四
@Desc: k-近邻算法
"""


import numpy
import operator

def createDataSet():
	data = numpy.array([[1,1.1],[1,1],[0,0],[0,1]])
	labels = ["A","A","B","B"]
	return data,labels

# sqr((x1-x2)**2 + (y1-y2)**2)
def classify0(data,labels,k,x):
	rowNum = data.shape[0]
	newX = numpy.tile(x, (rowNum,1))
	
	# 欧式距离计算
	diff1 = newX - data
	diff2 = diff1 ** 2
	diff3 = diff2.sum(axis = 1)
	diff4 = numpy.sqrt(diff3)

	# 按照value值大小，返回索引
	sortedDistance = diff4.argsort()

	classCount = dict()
	for i in range(k):
		voteLabel = labels[sortedDistance[i]]
		classCount[voteLabel] = classCount.get(voteLabel,0) + 1

	# 字典排序
	sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)

	return sortedClassCount[0][0]

